package com.ken.elmssm.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ken.elmssm.bean.Admin;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author ken
 *
 */
public class LoginInterceptor implements HandlerInterceptor {
    private Logger logger = Logger.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Admin admin = (Admin) request.getSession().getAttribute("login_user");

        logger.info("preHandle================" + admin);
        String uri = request.getRequestURI();

        // 登录页面和登录操作不拦截
        if (admin != null || request.getRealPath("/").lastIndexOf("sys/admin/login") != -1
        || uri.endsWith(".html") || uri.contains("/images/")
        || uri.contains("/css/") || uri.contains("/js/")
        || uri.contains("/upload/")){

            /* if (userName != null || uri.endsWith(".html")) { */
            // 返回true表示不拦截
            return true;
        }
        response.sendRedirect(request.getContextPath()+"/login.html");
        // 返回false表示会被拦截
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        logger.info("postHandle================");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

        logger.info("afterCompletion================");
    }

}